package com.zg.nacos.manager;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/6/27 16:37
 */

@Service
public class NamingServiceManager {

    @Value("${spring.cloud.nacos.username}")
    private  String username;
    @Value("${spring.cloud.nacos.password}")
    private  String password;

    private final String serverAddr;
    private final Map<String, NamingService> namingServiceCache = new ConcurrentHashMap<>();

    public NamingServiceManager(
            @Value("${spring.cloud.nacos.server-addr}") String serverAddr) {
        this.serverAddr = serverAddr;
    }

    public NamingService getNamingService(String namespace) throws NacosException {
        return namingServiceCache.computeIfAbsent(namespace, ns -> {
            Properties properties = new Properties();
            properties.setProperty("serverAddr", serverAddr);
            properties.setProperty("username",username);
            properties.setProperty("password",password);
            properties.setProperty("namespace", ns);
            properties.put("failoverEnabled", true);
            try {

                return NacosFactory.createNamingService(properties);
            } catch (NacosException e) {
                throw new RuntimeException("创建NamingService失败", e);
            }
        });
    }
}
